<template>
  <div style="width:100%">
    <div v-if="isInChildren">
      <div v-for="item in valueArray" :key="item.id" class="wps_container">
        <div class="left">{{ item.name }}</div>
      </div>
    </div>
    <div v-else-if="isDesigner" class="wps_container">
      <el-button type="primary" class="ml-5">
        编辑正文
      </el-button>
    </div>
    <div v-else class="wps_container">
      <el-button v-if="mixEditable" type="primary" @click="editApp(Array.isArray(valueArray) && valueArray[0])">
        {{buttonText || '编辑正文'}}
      </el-button>
      <el-button v-else type="primary" @click="previewApp(Array.isArray(valueArray) && valueArray[0])">
        {{buttonText || '查看正文'}}
      </el-button>
    </div>
  </div>
</template>
<script>
// import localMethods from '../../mixins/localMethods'
import routerContextPath from '../../mixins/router-context-path.js'
import { installWpsAddin, _WpsInvoke } from 'base/utils'
export default {
  name:'wps',
  // mixins: [localMethods, routerContextPath],
  mixins: [ routerContextPath],
  props:{
    // fieldid,name,type
    value:'',
    mode: {
      default: "edit", // 编辑模式和 edit， 展示模式 view
    },
    isInChildren: {
      type: Boolean,
      default: false
    },
    fileName: {
      type: String,
      default: '公文.docx'
    },
    // 转ofd显示与否
    isSwitchOfd: {
      type: Boolean,
      default: false
    },
    // 创建文件方式
    uploadMethods: {
      type: String,
      default: 'create'
    },
    buttonText: {
      type: String,
      default: ''
    }
  },
  computed: {
    valueArray() {
      const arr = this.value && this.value.split(',').map(i => {
        const obj = i.split('/')
        return {
          id: obj[0],
          name: obj[1],
          type: obj[2]
        }
      }) || []
      console.log(arr,'==arr')
      return arr
    },
    typeOptions() {
      return this.options && this.options.filter(item => item.value !== 'f')
    },
    isDesigner(){
      return this.$attrs._source === 'designer'
    },
    mixEditable() {
      return !(this.$attrs.readonly || this.$attrs.disabled) && this.mode === "edit"
    },
    dispatchProxy(){
      if (Vue.prototype.dispatchProxy) {
        return Vue.prototype.dispatchProxy(this)
      } else {
        return this.dispatch
      }
    },
    userInfo() {
      const user = localStorage.getItem('user')
      return JSON.parse(user)
    },
    Authorization() {
      return this.userInfo.uniqueId
    },
    isLocalLoad() {
      return (this.userInfo.attributes && this.userInfo.attributes.Extra || '1') === '1'
    }
  },
  data() {
    return {
      options: [{
        label: '文字文件 (word)',
        value: 'w',
        types: ['doc' , 'dot' , 'wps' , 'wpt' , 'docx' , 'dotx' , 'docm' , 'dotm']
      }, {
        label: '表格文件 (excel)',
        value: 's',
        types: ['xls' , 'xlt' , 'et' , 'xlsx' , 'xltx' , 'xlsm' , 'xltm']
      }, {
        label: '演示文件 (ppt)',
        value: 'p',
        types: ['ppt' , 'pptx' , 'pptm' , 'ppsx' , 'ppsm' , 'pps' , 'potx' , 'potm' , 'dpt' , 'dps']
      }, {
        label: 'PDF文件',
        value: 'f',
        types: ['pdf']
      }],
      fileType: 'w',
      ofdId: '',
      downloadUrl: '',
      dialogVisiable: false
    }
  },
  watch: {
    value: {
      immediate: true,
      handler(val) {
        console.log(val,'===val')
      }
    }
  },
  created(){
    // installWpsAddin()
  },
  methods: {
    async localEditApp(item, type) {
        console.log(!type,'===!type')
          // const { origin } = window.location
        const origin  = 'http://121.36.242.165:28090'
      installWpsAddin()
      const userName = this.userInfo.userName
      const {id} = item
      const uploadPath = `${origin}/XFfileServer/fileSaveOrUpdate?userName=${userName}` + (id ? `&fileId=${id}` : '')
      if (!id) {
          // 本地创建doc文件
          this.isEdit = false
          const tempId = String(new Date().getTime()).slice(8,13)
          _WpsInvoke([{
            "NewDoc": {
                tempId,
                "uploadPath": uploadPath, // 保存文档上传接口
                "uploadFieldName": this.fileName || '公文.docx',
                "uploadFileName": this.fileName || '公文.docx',
                "picPath": '',
                "copyUrl": uploadPath,
                "userName": userName,
                "suffix": 'doc',
                "Authorization": this.Authorization,
                "newFileName": this.fileName || '公文.docx',
                "RevisionEnableFlag": true,
                "RevisionShowEnableFlag": true,
                "revisionCtrl": {
                    "bOpenRevision": true,
                    "bShowRevision": true
                },
            },
          }],
            true,
            "http://127.0.0.1:8000/iestart/jsplugins.xml",
            false,
            (data) => {
              this.$emit('input', JSON.parse(data)[0].id)
            })
        }else {
            this.isEdit = true
            // var filePath = window.location.origin + '/XFfileServer/fileDownload?id=' + id
            const filePath = `${origin}/XFfileServer/fileDownload?id=${id}`
            console.log('filePath',filePath)
            // http://121.36.242.165:28084/XFfileServer/fileDownload?id=6000e9b9-67ce-4428-aaf2-1a97534f45ee
            // http://121.36.242.165:22084/XFfileServer/fileUpload
            // var backupPath = prompt("请输入文档备份路径:")
            // E:\test_wps
              _WpsInvoke([{
                "OpenDoc": {
                    "uploadPath": uploadPath, // 保存文档上传接口
                    "fileName": filePath,
                    "uploadFieldName": this.uploadFieldName || '公文.doc',
                    "uploadFileName": this.uploadFieldName || '公文2.doc',
                    "picPath": '',
                    "copyUrl": uploadPath,
                    "userName": this.userInfo.userName,
                    "suffix": 'doc',
                    "Authorization": this.Authorization,
                    "RevisionEnableFlag": true,
                    "fileId": id,
                    "RevisionShowEnableFlag": true,
                    "revisionCtrl": {
                      "bOpenRevision": true,
                      "bShowRevision": true
                    },
                    "openType": { //文档打开方式
                      // 文档保护类型，-1：不启用保护模式，0：只允许对现有内容进行修订，
                      // 1：只允许添加批注，2：只允许修改窗体域(禁止拷贝功能)，3：只读
                      "protectType": type === 'preview' ? 3 : -1,
                      "password": "123456"
                  }
                }
            }],true,
            "http://127.0.0.1:8000/iestart/jsplugins.xml",
            false,
            (data) => {
              console.log('input', JSON.parse(data)[0].id)
            }) 
        }
    },
    async getFieldInfo(val) {
      const resp = await this.dispatchProxy(Vue.prototype.Controllers.AttachmentController.getAttachment, {
        attachmentId: val
      })
      if (!resp.error) {
        const { fileId, fileName, fileType} = resp.data
        const type = (this.options.find(o => o.types.includes(fileType)) || {}).value || 'other'
        const val = fileId + '/' + fileName + '/' + type
        this.$emit('input', fileId)
      }
    },
    async creatApp() {
      let resp = await this.dispatchProxy(Vue.prototype.Controllers.WPSController.createLink, {
        fileName: this.fileName.split('.')[0],
        type: this.fileType,
        userName: this.userInfo.userName
      })
      if (!resp.error) {
        const { id, name } = resp.data[0]
        this.$message.success(`创建成功${name || ''}`)
        const val = id + '/' + name + '/' + this.fileType
        this.$emit('input', id)
        this.$emit('addFile', resp.data[0])
        if (this.mixEditable) {
          await this.editApp({
            id: id,
            name
          })
        } else {
          await this.previewApp({
            id: id,
            name
          })
        }
      } else {
        this.$message.error(resp.error)
      }
    },
    getType(name = this.fileName) {
      const append = name.slice(name.lastIndexOf('.') + 1)
      if (['docx' , 'doc' , 'dot' , 'wps' , 'wpt' , 'dotx' , 'docm' ,'dotm' , 'rtf' , 'uot' , 'mht' , 'mhtml' ,'htm' , 'html' , 'xml'].includes(append)) {
        return 'w'
      } else if (['xls' , 'xlt' , 'et' , 'ett' , 'xlsx' , 'xltx' ,'csv' , 'xlsm' , 'xltm' , 'xlsb' , 'uos'].includes(append)) {
        return 's'
      } else if (['pptx' , 'ppt' , 'pot' , 'potx' , 'pps' , 'ppsx' , 'dps' ,'dpt' , 'pptm' , 'potm' , 'ppsm' , 'uop'].includes(append)) {
        return 'p'
      } else if (['pdf', 'ofd'].includes(append)) {
        return 'f'
      } else {
        return 'w'
      }
    },
    async previewApp(item = {}) {
      if (this.isLocalLoad) {
        this.localEditApp(item,'preview')
        return
      }
      const {id, name = this.fileName} = item
      console.log(name,'===name')
      if (!id) {
        await this.creatApp()
      } else {
        const resp = await this.dispatchProxy(Vue.prototype.Controllers.WPSController.getLinkView, {
          fileId: id,
          type: this.getType(name) || 'w',
          wThirdParams: this.userInfo.userName
        })
        const { msg, data, code } = resp.data
        if (code === 200) {
          // this.setToken(data.link)
          window.open(`${this.contextPath}/index.html#/preview/office?openLink=${encodeURIComponent(data.link)}&type=preview`)
          // window.open(data.link)
        } else {
          this.$message.error(msg)
        }
      }
    },
    async editApp(item = {}) {
      if (this.isLocalLoad) {
        this.localEditApp(item)
        return
      }
      const {id, name = this.fileName} = item
      if (!id) {
        await this.creatApp()
      } else {
        // const item = this.valueArray[0]
        const resp = await this.dispatchProxy(Vue.prototype.Controllers.WPSController.getLinkEdit, {
          fileId: id,
          type: this.getType(name) || 'w',
          wThirdParams: this.userInfo.userName
        })
        const { msg, data, code } = resp.data
        if (code === 200) {
          window.open(`${this.contextPath}/index.html#/preview/office?openLink=${encodeURIComponent(data.link)}&type=edit`)
        } else {
          this.$message.error(msg)
        }
      }
    },
    selectType(append) {
      
    },
    async uploadFile(file){
      let params=new FormData()
      params.append('attachments',file.file)
      params.append('userName', this.userInfo.userName)
      const resp = await this.dispatchProxy(Vue.prototype.Controllers.XFFileController.fileUpload, params)
      if (!resp.error && resp.data) {
        const { id, name } = resp.data[0]
        const fileType = name.slice(name.lastIndexOf('.') + 1)
        const type = (this.options.find(o => o.types.includes(fileType)) || {}).value || 'other'
        const val = id + '/' + name + '/' + type
        this.$emit('input', id)
        this.$emit('addFile', resp.data[0])
        this.fileList = []
        this.$message({
            type: 'success',
            message: '上传成功!'
        })
      }
    },
    async switchOfd(item) {
      // const prefix = 'http://121.36.242.165:28084'
      const prefix = window.location.origin
      let params = new FormData()
      params.append('taskId',  String(Math.random()*100000000).slice(0,7))
      params.append('docFilename', item.name)
      params.append('docUrl', `${prefix}/XFfileServer/fileDownload?id=${item.id}`)
      params.append('target', 'ofd')
      const resp = await this.dispatchProxy(Vue.prototype.Controllers.WPSController.convertFile, params)
      const { msg, data, code } = resp.data
      if (code === 200) {
        await this.downloadFormat(data)
      } else {
        this.$message.error(msg)
      }
    },
    // 根据id下载
    // downloadself(item) {
    //   // AjaxUtil.config.responseType = "blob";
    //   AjaxUtil.ajax({
    //     responseType : 'blob',
    //     // url: window.location.origin + `/XFfileServer/fileDownload?id=${fileId}`,
    //     url: `/XFfileServer/fileDownload?id=${fileId}`,
    //     method: 'GET',
    //     data: {},
    //   }).then(resp => {
    //   console.log(resp,'=======下载resp')
    //       let url = window.URL.createObjectURL(resp.data);  //生成文件流下载链接
    //       let a = document.createElement('a');      //创建一个a标签用来跳转
    //       a.href = url;                             // a标签 href  赋值 链接  
    //       a.download = fileName;                  //设置下载文件的文件名和文件格式
    //       document.body.appendChild(a);             //将标签DOM，放置页面
    //       a.click();                              
    //       window.URL.revokeObjectURL(url);     //释放 url 对象内存
    //       document.body.removeChild(a);
    //   })
    //   AjaxUtil.config.responseType = "json";
    // },
    async downloadFormat(item) {
      const { downloadId, routerKey } = item
      const data = {
        downloadId,
        routeKey: routerKey,
        userName: this.userInfo.userName,
        target: 'ofd',
        fileName: this.fileName
      }
      const resp = await this.dispatchProxy(Vue.prototype.Controllers.WPSController.operateDocumentResultDownload, data)
      if (!resp.error) {
        this.downloadUrl = resp.data.downloadUrl
        this.ofdId = resp.data.fileId
        this.openAction()
      }
    },
    openAction() {
      this.dialogVisiable = true
    },
    previewOfd() {
      this.previewApp({
        id: this.ofdId,
        type: 'f'
      })
    },
    handleClose() {
      this.dialogVisiable = false
    },
    error(err, file, fileList) {
      this.$emit('uploadError',{err, file, fileList})
    },
    success(response, file, fileList) {

    },
  }
}
</script>
<style lang="scss" scoped>
  // .wps_container {
  //   display: flex;
  //   .left {
  //     flex: 1;
  //   }
  //   .el-button {
  //     margin-left: 5px;
  //   }
  // }
  a {
    text-decoration: none;
    color: #fff;
  }
  a:link {
    color: #fff;
  }
  a:hover {
    color: #fff;
  }
</style>